﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Studio77.RuneMaster.Entities;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using Studio77.RuneMaster.Core;
using System.Windows.Media.Imaging;
using Studio77.RuneMaster.Entities.GameRecord;
using Studio77.RuneMaster.Views;
using Microsoft.Phone.Tasks;
using Studio77.RuneMaster.Utils;
using Com.MSN.Ads.WindowsPhone.SDK.View;
using System.Diagnostics;
using CN.SmartMad.Ads.WindowsPhone.WPF;

namespace Studio77.RuneMaster.Pages
{
    public partial class GamePage : PhoneApplicationPage
    {
        public static GamePage Instance = null;

        int currentScore = 0;
        int currentSprite = 0;
        int currentSumCombo = 0;
        StageInfo currentStageInfo = null;

        List<ToolItemInGame> tools = new List<ToolItemInGame>();

        /// <summary>
        /// 游戏状态
        /// 0-未开始 1-游戏进行中 2-游戏暂停 3-完成子关卡 4-完成Stage 5-子关卡失败 6-GameOver
        /// </summary>
        int gameStatus = 0;

        public GamePage()
        {
            InitializeComponent();
            Instance = this;

            tools.Clear();
            tools.Add(tool1);
            tools.Add(tool2);
            tools.Add(tool3);
            tools.Add(tool4);

            this.imgQuickStart.MouseLeftButtonDown += imgQuickStart_MouseLeftButtonDown;

            StageManager.Instance.LaunchCount = StageManager.Instance.LaunchCount + 1;

            this.Loaded += GamePage_Loaded;


        }

        DispatcherTimer mokaAdsSwitchTimer;
        int currentMokaAdIndex = 0;
        int totalMokaAdCount = 2;

        bool usemoka = true;

        void GamePage_Loaded(object sender, RoutedEventArgs e)
        {
            this.Loaded -= GamePage_Loaded;

            //AdView.SetApplicationID("ea27bea4a3a51f83");

            // SmartMad AdView Dynamic Load
            //SmartMad.Ads.WindowsPhone7.WPF.AdView adViewHandle = new SmartMad.Ads.WindowsPhone7.WPF.AdView();
            //adViewHandle.AdPositionID = "90026983";
            //adViewHandle.AdInterval = 30;
            //adViewHandle.AdAnimation = SmartMad.Ads.WindowsPhone7.WPF.AdAnimationType.AdAnimationFlipFromLeft;
            //adViewHandle.IsDebugMode = true;
            //adViewHandle.AdViewEvent +=
            //    new SmartMad.Ads.WindowsPhone7.WPF.AdView.AdViewEventChanged(adViwe1Event);
            //adViewHandle.AdViewFullscreenEvent +=
            //    new SmartMad.Ads.WindowsPhone7.WPF.AdView.AdViewFullscreenEventChanged(adView1FullscreenEvent);
            //gridAd.Children.Add(adViewHandle);

            //魔卡广告切换Timer
            mokaAdsSwitchTimer = new DispatcherTimer();

            //获取间隔参数
            int intervalSec = 30;
            string secStr = UmengSDK.UmengAnalytics.GetOnlineParam("moka_banner_switch_sec");
            if (!int.TryParse(secStr, out intervalSec))
            {
                intervalSec = 30;
            }

            mokaAdsSwitchTimer.Interval = TimeSpan.FromSeconds(intervalSec);
            mokaAdsSwitchTimer.Tick += mokaAdsSwitchTimer_Tick;
            mokaAdsSwitchTimer.Start();

            bool useSmartmad = true;
            String usemokaStr = UmengSDK.UmengAnalytics.GetOnlineParam("usemoka");
            //0-关闭 1-同时开启 2-开启banner 3-开启开屏
            if (usemokaStr == "1" || usemokaStr == "2")
            {
                usemoka = true;
                if (StageManager.Instance.TurnMoka)
                {
                    //移动moka到最前面，而且不显示亿动
                    gridAd.Children.Remove(imgBanner);
                    gridAd.Children.Add(imgBanner);
                    useSmartmad = false;
                }
                StageManager.Instance.TurnMoka = !StageManager.Instance.TurnMoka;
                currentMokaAdIndex = 0;
                switchMokaAdImage();
            }
            else if (usemokaStr == "0" || usemokaStr == "3")
            {
                this.imgBanner.Visibility = System.Windows.Visibility.Collapsed;
                usemoka = false;
            }
            else
            {
                usemoka = false;
            }


            if (useSmartmad)
            {
                InitSmartBannerAd();
                InitMsnAd();
            }
            else
            {
                gridSmartAd.Visibility = System.Windows.Visibility.Collapsed;
                gridMsnAd.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        /// <summary>
        /// 更新魔卡广告的banner
        /// </summary>
        private void switchMokaAdImage()
        {
            BitmapImage bitmap = new BitmapImage(new Uri(@"\Images\banner" + (currentMokaAdIndex + 1).ToString() + ".jpg", UriKind.RelativeOrAbsolute));
            this.imgBanner.Source = bitmap;
        }

        void mokaAdsSwitchTimer_Tick(object sender, EventArgs e)
        {
            currentMokaAdIndex++;
            currentMokaAdIndex = currentMokaAdIndex % totalMokaAdCount;
            switchMokaAdImage();
        }

        void imgQuickStart_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            if (gameStatus == 0)
            {
                SoundManager.PlayEffect(SoundManager.buttonClick);
                StartGame();
                this.imgQuickStart.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (gameStatus == 1)
            {
                //暂停
                this.StoryboardShowPause.Begin();

                //判断是否能够Restart
                if (StageManager.Instance.CurrentRestartChange > 1)
                {
                    this.btnPauseRestart.IsEnabled = true;
                }
                else
                {
                    this.btnPauseRestart.IsEnabled = false;
                }

                gameStatus = 2;
            }
            else if (gameStatus == 2)
            {
                //rusume
                this.StoryboardHidePause.Begin();
                gameStatus = 1;
            }
            else if (gameStatus == 3)
            {
                //下一个子关卡
                btnNext_Click_1(null, null);
            }
            else if (gameStatus == 4 || gameStatus == 6)
            {
                //返回关卡选择菜单
                btnReturn_Click_1(null, null);
            }
            else if (gameStatus == 5)
            {
                //重试该子关卡
                btnRetry_Click_1(null, null);
            }
            e.Cancel = true;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);

            if (gameStatus == 4 || gameStatus == 6)
            {
                //清除游戏记录
                StageManager.Instance.SavedGameRecord = null;
            }
            else
            {
                SaveGameStaus();
            }
        }

        /// <summary>
        /// 保存进度信息
        /// </summary>
        private void SaveGameStaus()
        {
            SavedGameRecord record = new SavedGameRecord();
            record.CurrentScore = currentScore;
            record.GameMode = StageManager.Instance.CurrentGameMode;
            record.LeftLifeCount = StageManager.Instance.CurrentRestartChange;
            record.LeftSpiritCount = currentSprite;
            record.StageIndex = StageManager.Instance.CurrentStageIndex;
            record.SubStageIndex = StageManager.Instance.CurrentSubStageIndex;
            //道具信息保存
            record.ToolSlotStatus = StageManager.Instance.CurrentToolSlotInfo;
            record.UsedToolStatus = StageManager.Instance.CurrentUsedTool;

            record.Runes = gameCanvas.GetCurrentRuneInfos();

            if (record.Runes != null)
            {
                //设置
                StageManager.Instance.SavedGameRecord = record;
            }

            SaveGameHighlights();

            //背景音效
            AudioPlayHelper.PlayBackground("background.mp3");
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            //背景音效
            AudioPlayHelper.PlayBackground("background.mp3");

            if (gameStatus == 0)
            {
                string isNewGame = "1";
                NavigationContext.QueryString.TryGetValue("isNewGame", out isNewGame);

                if (isNewGame == "1")
                {
                    //从第一个子关卡开始
                    StageManager.Instance.CurrentSubStageIndex = 1;

                    if (StageManager.Instance.CurrentStageIndex == "1" && StageManager.Instance.CurrentGameMode == "e")
                    {
                        this.imgQuickStart.Visibility = System.Windows.Visibility.Visible;
                    }
                    else
                    {
                        this.imgQuickStart.Visibility = System.Windows.Visibility.Collapsed;
                        StartGame();
                    }
                }
                else
                {
                    //继续上次的游戏
                    LoadLastGame();
                }

            }
        }

        /// <summary>
        /// 载入上次的游戏进度
        /// </summary>
        private void LoadLastGame()
        {
            //动画
            this.gameCanvas.IsHitTestVisible = true;
            this.StoryboardShowGameCanvas.BeginTime = TimeSpan.FromMilliseconds(300);
            this.StoryboardShowGameCanvas.Begin();
            string uri = uri = "/Images/start.png";
            BitmapImage bitmap = new BitmapImage(new Uri(uri, UriKind.RelativeOrAbsolute));
            imgGamingTip.Source = bitmap;
            this.StoryboardShowGamingTip.Begin();

            String stageKey = GetCurrentStageKey();

            //获取关卡信息
            if (StageManager.Instance.StageInfos.ContainsKey(stageKey))
            {
                StageInfo stageInfo = StageManager.Instance.StageInfos[stageKey];
                currentStageInfo = stageInfo;

                SavedGameRecord record = StageManager.Instance.SavedGameRecord;
                toolbar.InitToolBar(stageInfo);
                toolbar.AddScore(record.CurrentScore);
                toolbar.SetLeftSprite(record.LeftSpiritCount);
                currentScore = record.CurrentScore;
                currentSprite = record.LeftSpiritCount;
                currentSumCombo = 0;

                //道具信息保存
                StageManager.Instance.CurrentToolSlotInfo = record.ToolSlotStatus;
                StageManager.Instance.CurrentUsedTool = record.UsedToolStatus;

                //更新生命数量
                UpdateGameRestartChange();

                this.gameCanvas.InitGame(record.Runes);
                gameStatus = 1;

                //判断游戏类型
                JudgeSuccessFail();
                UpdateWaringStatus();

                //更新道具状态
                UpdateToolUI();
                UpdateUsedToolUI();
            }
            else
            {
                //出错
                //返回Stage选择
                this.NavigationService.Navigate(new Uri("/Pages/StagePage.xaml?Mode=" + StageManager.Instance.CurrentGameMode, UriKind.RelativeOrAbsolute));
            }

            GotoMarketToComment();
        }

        private void StartGame()
        {
            this.gameCanvas.IsHitTestVisible = true;
            //动画
            this.StoryboardShowGameCanvas.BeginTime = TimeSpan.FromMilliseconds(300);
            this.StoryboardShowGameCanvas.Begin();
            string uri = uri = "/Images/start.png";
            BitmapImage bitmap = new BitmapImage(new Uri(uri, UriKind.RelativeOrAbsolute));
            imgGamingTip.Source = bitmap;
            this.StoryboardShowGamingTip.Begin();

            String stageKey = GetCurrentStageKey();

            //获取关卡信息
            if (StageManager.Instance.StageInfos.ContainsKey(stageKey))
            {
                StageInfo stageInfo = StageManager.Instance.StageInfos[stageKey];
                currentStageInfo = stageInfo;

                toolbar.InitToolBar(stageInfo);
                currentScore = 0;
                currentSprite = stageInfo.SpriteCount;
                currentSumCombo = 0;

                this.gameCanvas.InitGame();
                gameStatus = 1;
                UpdateWaringStatus();

                //显示道具情况
                UpdateToolUI();
            }

            GotoMarketToComment();
        }

        /// <summary>
        /// 更新道具状态
        /// </summary>
        internal void UpdateToolUI()
        {
            foreach (var slot in StageManager.Instance.CurrentToolSlotInfo.Keys)
            {
                if (StageManager.Instance.CurrentToolSlotInfo[slot] != null)
                {
                    var toolInfo = StageManager.Instance.CurrentToolSlotInfo[slot];
                    //有道具
                    tools[slot].SetTool(toolInfo.Type);
                    tools[slot].SetToolCount(toolInfo.LeftCount);
                    tools[slot].Visibility = System.Windows.Visibility.Visible;
                }
                else
                {
                    //没有道具
                    tools[slot].Visibility = System.Windows.Visibility.Collapsed;
                }
            }
        }

        /// <summary>
        /// 更新使用的道具UI
        /// </summary>
        internal void UpdateUsedToolUI()
        {
            toolbar.UpdateUsedToolUI();
        }

        private void UpdateGameRestartChange()
        {
            switch (StageManager.Instance.CurrentRestartChange)
            {
                case 3:
                    this.heart1.Visibility = System.Windows.Visibility.Visible;
                    this.heart3.Visibility = System.Windows.Visibility.Visible;
                    this.heart2.Visibility = System.Windows.Visibility.Visible;
                    break;
                case 2:
                    this.heart1.Visibility = System.Windows.Visibility.Visible;
                    this.heart3.Visibility = System.Windows.Visibility.Collapsed;
                    this.heart2.Visibility = System.Windows.Visibility.Visible;
                    break;
                case 1:
                    this.heart1.Visibility = System.Windows.Visibility.Visible;
                    this.heart3.Visibility = System.Windows.Visibility.Collapsed;
                    this.heart2.Visibility = System.Windows.Visibility.Collapsed;
                    break;
                case 0:
                    this.heart1.Visibility = System.Windows.Visibility.Collapsed;
                    this.heart3.Visibility = System.Windows.Visibility.Collapsed;
                    this.heart2.Visibility = System.Windows.Visibility.Collapsed;
                    break;
            }

        }

        internal void AddScore(int score)
        {
            this.toolbar.AddScore(score);
            currentScore += score;
        }

        internal void AddCombo()
        {
            currentSumCombo++;
        }

        internal void AddSprite(int spriteCount)
        {
            currentSprite += spriteCount;
            this.toolbar.AddSprite(spriteCount);
            UpdateWaringStatus();
        }

        internal void SubSprite()
        {
            currentSprite--;
            this.toolbar.SubSprite(1);
            UpdateWaringStatus();
        }

        private void UpdateWaringStatus()
        {
            if (currentSprite <= 3)
            {
                //显示Waring
                if (this.imageWaring.Visibility == System.Windows.Visibility.Collapsed)
                {
                    this.imageWaring.Visibility = System.Windows.Visibility.Visible;
                    this.StoryboardWaring.RepeatBehavior = RepeatBehavior.Forever;
                    this.StoryboardWaring.Begin();
                }

            }
            else
            {
                //隐藏Waring
                this.imageWaring.Visibility = System.Windows.Visibility.Collapsed;
                this.StoryboardWaring.Stop();
            }
        }

        internal void JudgeSuccessFail()
        {
            if (currentScore >= currentStageInfo.AimScore)
            {
                //关卡成功
                string uri = uri = "/Images/Complete.png";
                BitmapImage bitmap = new BitmapImage(new Uri(uri, UriKind.RelativeOrAbsolute));
                imgGamingTip.Source = bitmap;
                this.StoryboardShowGamingTip.Begin();
                Win();

            }
            else if (currentSprite <= 0)
            {
                //关卡失败
                string uri = uri = "/Images/NoSprite.png";
                BitmapImage bitmap = new BitmapImage(new Uri(uri, UriKind.RelativeOrAbsolute));
                imgGamingTip.Source = bitmap;
                this.StoryboardShowGamingTip.Begin();

                Lose();
            }
        }

        private void Lose()
        {
            SoundManager.PlayEffect(SoundManager.nosprite);
            //隐藏Waring
            this.imageWaring.Visibility = System.Windows.Visibility.Collapsed;
            this.StoryboardWaring.Stop();
            this.gameCanvas.IsHitTestVisible = false;
            this.StoryboardHideGameCanvas.BeginTime = TimeSpan.FromMilliseconds(500);
            this.StoryboardHideGameCanvas.Begin();

            //TODO lc 扣除一次重试机会
            StageManager.Instance.CurrentRestartChange--;
            UpdateGameRestartChange();
            if (StageManager.Instance.CurrentRestartChange > 0)
            {
                gameStatus = 5;
                //StageClear
                String uri = "/Images/StageFail.png";
                BitmapImage bitmap = new BitmapImage(new Uri(uri, UriKind.RelativeOrAbsolute));
                ImgStatus.Source = bitmap;

                //按钮状态
                this.btnNext.Visibility = System.Windows.Visibility.Collapsed;
                this.btnRetry.Visibility = System.Windows.Visibility.Visible;
                this.btnReturn.Visibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                gameStatus = 6;
                //StageClear
                String uri = "/Images/GameOver.png";
                BitmapImage bitmap = new BitmapImage(new Uri(uri, UriKind.RelativeOrAbsolute));
                ImgStatus.Source = bitmap;

                //按钮状态
                this.btnNext.Visibility = System.Windows.Visibility.Collapsed;
                this.btnRetry.Visibility = System.Windows.Visibility.Collapsed;
                this.btnReturn.Visibility = System.Windows.Visibility.Visible;

                //umeng事件
                UmengSDK.UmengAnalytics.TrackEvent("GameOver", GetCurrentStageKey());
            }
            //显示分数
            ShowScoreG();
            this.StoryboardShowStatus.BeginTime = TimeSpan.FromMilliseconds(1000);
            this.StoryboardShowStatus.Begin();
            //隐藏暂停
            this.StoryboardHidePause.Begin();

            SaveGameHighlights();
        }

        private void SaveGameHighlights()
        {
            //记录最高分,及保存游戏记录
            if (StageManager.Instance.GameHightlightsRecord.HighScore < currentScore)
            {
                StageManager.Instance.GameHightlightsRecord.HighScore = currentScore;
            }
            StageManager.Instance.SaveGameHightlightsRecord();
        }

        private void Win()
        {
            //隐藏Waring
            this.imageWaring.Visibility = System.Windows.Visibility.Collapsed;
            this.StoryboardWaring.Stop();
            this.gameCanvas.IsHitTestVisible = false;
            this.StoryboardHideGameCanvas.BeginTime = TimeSpan.FromMilliseconds(500);
            this.StoryboardHideGameCanvas.Begin();

            if (StageManager.Instance.CurrentSubStageIndex == 5)
            {
                SoundManager.PlayEffect(SoundManager.stageClear);
                gameStatus = 4;
                //StageClear
                String uri = "/Images/StageClear.png";
                BitmapImage bitmap = new BitmapImage(new Uri(uri, UriKind.RelativeOrAbsolute));
                ImgStatus.Source = bitmap;

                //按钮状态
                this.btnNext.Visibility = System.Windows.Visibility.Collapsed;
                this.btnRetry.Visibility = System.Windows.Visibility.Collapsed;
                this.btnReturn.Visibility = System.Windows.Visibility.Visible;

                //解锁后续的Stage
                int currStageIndex = int.Parse(StageManager.Instance.CurrentStageIndex);
                if (currStageIndex < 10)
                {
                    string nextStageKey = StageManager.Instance.CurrentGameMode + "_" + (currStageIndex + 1);
                    if (!StageManager.Instance.StageUnlockStatus.ContainsKey(nextStageKey))
                    {
                        StageManager.Instance.StageUnlockStatus.Add(nextStageKey, true);
                    }
                    StageManager.Instance.StageUnlockStatus[nextStageKey] = true;

                    StageManager.Instance.SaveStageUnlockInfo();
                }

                //umeng事件
                UmengSDK.UmengAnalytics.TrackEvent("StageClear", GetCurrentStageKey());

            }
            else
            {
                SoundManager.PlayEffect(SoundManager.levelup);
                gameStatus = 3;
                //StageClear
                String uri = "/Images/StageSuccess.png";
                BitmapImage bitmap = new BitmapImage(new Uri(uri, UriKind.RelativeOrAbsolute));
                ImgStatus.Source = bitmap;

                //按钮状态
                this.btnNext.Visibility = System.Windows.Visibility.Visible;
                this.btnRetry.Visibility = System.Windows.Visibility.Collapsed;
                this.btnReturn.Visibility = System.Windows.Visibility.Collapsed;
            }

            //显示分数
            ShowScoreG();
            this.StoryboardShowStatus.BeginTime = TimeSpan.FromMilliseconds(1000);
            this.StoryboardShowStatus.Begin();
            //隐藏暂停
            this.StoryboardHidePause.Begin();

            SaveGameHighlights();
        }

        private void ShowScoreG()
        {
            this.txtStatusStageName.Text = currentStageInfo.StageName;
            this.txtScore.Text = currentScore.ToString();
            int scoreG = currentScore / 10;
            this.txtScoreG.Text = scoreG.ToString() + " G";
            this.txtCombo.Text = currentSumCombo.ToString();
            int comboG = currentSumCombo * 100;
            this.txtComboG.Text = comboG + " G";

            int sprite = currentSprite;
            int spriteG = currentSprite * 50;

            this.txtSprite.Text = sprite.ToString();
            this.txtSpriteG.Text = spriteG + " G";

            int sumG = comboG + scoreG + spriteG;

            this.txtAddG.Text = "+ " + sumG.ToString() + " G";
            this.txtTotalG.Text = "TOTAL: " + (sumG + StageManager.Instance.TotalG) + " G";
            StageManager.Instance.TotalG += sumG;
        }

        /// <summary>
        /// 获取当前关卡Key
        /// </summary>
        /// <returns></returns>
        private string GetCurrentStageKey()
        {
            return StageManager.Instance.CurrentGameMode
                + "_" + StageManager.Instance.CurrentStageIndex
                + "_" + StageManager.Instance.CurrentSubStageIndex;
        }

        private void btnNext_Click_1(object sender, RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.buttonClick);
            //下一个子关卡
            StageManager.Instance.CurrentSubStageIndex++;
            //再次开始游戏
            StartGame();
            StoryboardHideStatus.Begin();
            StoryboardHidePause.Begin();
        }

        private void btnRetry_Click_1(object sender, RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.buttonClick);
            //再试一次
            StartGame();
            StoryboardHideStatus.Begin();
            StoryboardHidePause.Begin();
        }

        private void btnPauseRestart_Click_1(object sender, RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.buttonClick);
            StageManager.Instance.CurrentRestartChange--;
            UpdateGameRestartChange();

            //再试一次
            StartGame();
            StoryboardHideStatus.Begin();
            StoryboardHidePause.Begin();
        }

        private void btnReturn_Click_1(object sender, RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.buttonClick);
            //返回Stage选择
            this.NavigationService.Navigate(new Uri("/Pages/StagePage.xaml?Mode=" + StageManager.Instance.CurrentGameMode, UriKind.RelativeOrAbsolute));
        }

        private void btnReturnToMain_Click_1(object sender, RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.buttonClick);
            //返回主菜单
            this.NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.RelativeOrAbsolute));
        }

        private void btnResume_Click_1(object sender, RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.buttonClick);
            this.StoryboardHidePause.Begin();
            if (gameStatus == 2)
            {
                gameStatus = 1;
            }
        }

        internal void ReArrange()
        {
            SoundManager.PlayEffect(SoundManager.buttonClick);
            //做个动画
            this.StoryboardRearrange.Begin();
            gameCanvas.ReArrange();
        }

        internal void CollectAllSpirit()
        {
            gameCanvas.CollectAllSprite();
        }

        internal void CreateNewSpiritRune()
        {
            gameCanvas.CreateNewSpiritRune();
        }

        /// <summary>
        /// 去市场评价
        /// </summary>
        private void GotoMarketToComment()
        {
            if (!StageManager.Instance.IsCommented &&
                ((StageManager.Instance.LaunchCount == 10) || StageManager.Instance.LaunchCount % 28 == 0))
            {
                if (MessageBox.Show("喜欢这款游戏吗? 如果是，那请给我们一个五星好评吧，谢谢您对我们的支持", "评分", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
                    marketplaceReviewTask.Show();
                    StageManager.Instance.IsCommented = true;
                }
                else
                {
                    StageManager.Instance.LaunchCount = StageManager.Instance.LaunchCount + 1;
                }
            }
        }

        private void adControl_ErrorOccurred(object sender, Microsoft.Advertising.AdErrorEventArgs e)
        {

        }

        private void adControl_AdRefreshed(object sender, EventArgs e)
        {

        }

        bool isLoadedMsn = false;

        private void InitMsnAd()
        {
            if (!isLoadedMsn)
            {
                string adSpaceId = "NzUwfDc5N3wyNDg5fDE=";//此处填写在MSN微软移动广告平台上申请的应用程序Id,Sample代码中的applicationId为测试Id，仅限于测试使用，不参与计费
                Thickness adPosition = new Thickness();//定义广告banner的位置。
                adPosition.Left = 0;
                adPosition.Top = 0;
                adPosition.Right = 0;
                adPosition.Bottom = 0;
                AdControl adControl = new AdControl(this);
                adControl.InitAd(adPosition, adSpaceId);//初始化广告banner
                adControl.AdReveiceEvent += new AdReveiceHandler(adControl_AdReveiceEvent);//广告接收成功事件
                adControl.AdFailedEvent += new AdFailedHandler(adControl_AdFailedEvent);//广告接收失败事件
                adControl.LeaveApplicationEvent += new LeaveApplicationHandler(LeaveApplicationHandler);//广告即将离开应用程序事件
                adControl.PresentScreenEvent += new PresentScreenHandler(adControl_PresentScreenEvent);//广告即将跳转网页事件
                adControl.DismissScreenEvent += new DismissScreenHandler(adControl_DismissScreenEvent);//广告网页返回事件
                gridMsnAd.Children.Add(adControl);//注意：不要忘了将广告banner加到应用程序中。
                adControl.LoadAd();//开始请求广告
                isLoadedMsn = true;
            }
        }

        public void adControl_AdReveiceEvent(AdControl adControl)
        {
            Debug.WriteLine("---------MSNLog--------adView_AdReveiceEvent");

            //移除微软广告
            Dispatcher.BeginInvoke(() =>
                {
                    try
                    {
                        if (this.adControlMicrosoft != null)
                        {
                            gridAd.Children.Remove(adControlMicrosoft);
                            adControlMicrosoft = null;
                        }
                        if (this.gridAd.Children.Contains(gridSmartAd))
                        {
                            this.gridAd.Children.Remove(gridSmartAd);
                        }
                        if (!this.gridAd.Children.Contains(gridMsnAd))
                        {
                            this.gridAd.Children.Add(gridMsnAd);
                        }
                    }
                    catch (Exception)
                    {
                    }
                });
        }
        public void adControl_PresentScreenEvent(AdControl adControl)
        {
            Debug.WriteLine("---------MSNLog --------adView_PresentScreenEvent");
        }
        public void adControl_DismissScreenEvent(AdControl adControl)
        {
            Debug.WriteLine("---------MSNLog--------adControl_DismissScreenEvent");
        }
        public void adControl_AdFailedEvent(ErrorCode errorCode, AdControl adControl)
        {
            Dispatcher.BeginInvoke(() =>
            {
                if (this.gridAd.Children.Contains(gridMsnAd))
                {
                    this.gridAd.Children.Remove(gridMsnAd);
                }
            });
        }
        public void LeaveApplicationHandler(AdControl adControl)
        {
            Debug.WriteLine("---------MSNLog --------LeaveApplicationHandler");
        }

        private void Image_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            if (currentMokaAdIndex == 0)
            {
                //跳转到魔卡幻想
                webBrowserTask.Uri = new Uri("http://bj.adserve.ifreeteam.com:9090/advertise/ad/receive.json?id=c035da4065183dbec79ffbe43fa11301ac619c2b8fdd723b692ae4b7915b3ce7", UriKind.Absolute);
            }
            else
            {
                //跳转到千魔斩
                webBrowserTask.Uri = new Uri("http://bj.adserve.ifreeteam.com:9090/advertise/ad/receive.json?id=5fc22bb64e05cb93477f153d9d61cb409179c3036db5ba85446dde582ec3c345", UriKind.Absolute);
            }
            webBrowserTask.Show();
        }

        #region 亿动广告

        SMAdBannerView ad2 = null;

        private void InitSmartBannerAd()
        {
            if (null == ad2)
            {
                ad2 = new SMAdBannerView("90032651");
                ad2.AdBannerAnimationType =
                    SMAdBannerAnimationType.BANNER_ANIMATION_TYPE_FADEINOUT;
                ad2.AdBannerReceived += new EventHandler(ad2_AdBannerReceived);
                ad2.AdBannerReceiveFailed +=
                    new EventHandler<SMAdEventCode>(ad2_AdBannerReceiveFailed);

                ad2.VerticalAlignment = VerticalAlignment.Top;
                gridSmartAd.Children.Add(ad2);
            }

        }

        private void ad2_AdBannerReceived(object sender, EventArgs e)
        {
            //移除微软广告
            Dispatcher.BeginInvoke(() =>
            {
                if (gridSmartAd != null)
                {
                    try
                    {
                        this.gridSmartAd.Visibility = System.Windows.Visibility.Visible;
                        if (this.adControlMicrosoft != null)
                        {
                            gridAd.Children.Remove(adControlMicrosoft);
                            adControlMicrosoft = null;
                        }
                        this.imgBanner.Visibility = System.Windows.Visibility.Collapsed;
                        this.gridMsnAd.Visibility = System.Windows.Visibility.Collapsed;
                        if (!this.gridAd.Children.Contains(gridSmartAd))
                        {
                            this.gridAd.Children.Add(gridSmartAd);
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            });
        }

        private void ad2_AdBannerReceiveFailed(object sender, SMAdEventCode code)
        {
            Dispatcher.BeginInvoke(() =>
            {
                try
                {
                    this.imgBanner.Visibility = System.Windows.Visibility.Visible;
                    this.gridSmartAd.Visibility = System.Windows.Visibility.Collapsed;
                    this.gridMsnAd.Visibility = System.Windows.Visibility.Visible;
                    if (this.gridAd.Children.Contains(gridSmartAd))
                    {
                        this.gridAd.Children.Remove(gridSmartAd);
                    }
                }
                catch (Exception)
                {

                }
            });
        }

        #endregion



        //private void adView1_AdViewEvent(object sender, AdViewEventArgs args)
        //{
        //    //亿动有广告，则隐藏可能存在的微软广告
        //    if (args.code == AdViewEventCode.EVENT_NEWAD)
        //    {
        //        if (this.adControl != null)
        //        {
        //            gridAd.Children.Remove(adControl);
        //            adControl = null;
        //        }
        //        if (this.adView1 != null && this.adView1.Visibility != System.Windows.Visibility.Visible)
        //        {
        //            this.adView1.Visibility = System.Windows.Visibility.Visible;
        //        }
        //    }
        //    else
        //    {
        //        if (this.adControl != null)
        //        {
        //            this.adControl.Visibility = System.Windows.Visibility.Visible;
        //        }
        //        if (this.adView1 != null)
        //        {
        //            this.adView1.Visibility = System.Windows.Visibility.Collapsed;
        //        }
        //    }
        //}

        //private void adView1_AdViewFullscreenEvent(object sender, AdViewFullscreenEventArgs args)
        //{

        //}

    }
}